package com.itic.appbase.applications.files.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itic.appbase.applications.files.utils.FileHelper;
import com.itic.appbase.applications.files.utils.ZipHelper;
import com.itic.appbase.framework.common.basevo.User;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.StringHelper;

/**
 * 文件管理
 * <p>Company: itic</p>
 * @author: shijun
 * @date: 2015年5月11日 下午1:28:40
 * @version: V1.0
 */
public class FileManagerServlet extends HttpServlet {
    
    private static final long serialVersionUID = 1L;
    private static final Logger log = LoggerFactory.getLogger(FileManagerServlet.class);
    private static final boolean DBFLAG = true;//文件信息是否保存库，存库true,不存库false
    private static final String CHARACTER_ENCODING = "UTF-8";
    private static final String FILE_PATH = "filePath";
    private static final String IS_CACHE = "no-cache";
    private static final String CACHE_CONTROL = "Cache-Control";
    private static final String ZZJGDM = "zzjgdm";
    
    
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }
    
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding(CHARACTER_ENCODING);
        String methodName = request.getParameter("method");
        try {
            if (StringHelper.isNotBlank(methodName)) {
                log.info("[FileManagerServlet | service] execute method: methodName= " + methodName);
                User user = findUserSession(request);
                if(null==user){//判断用户是否存在
                    log.error("[FileManagerServlet | service] 用户未登录");
                    responseJson(response, ResponseCode.NOT_LOGIN.getCode()); 
                }else{
                    Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
                    method.invoke(this, request, response);   
                }
            } else {
                log.error("param 'method' can not be null!");  
                responseJson(response, ResponseCode.NO_METHOD.getCode()); 
            }
        } catch (Exception e) {
            log.error("执行方法出错",e);
            try {
                responseJson(response, ResponseCode.NO_METHOD.getCode());
            } catch (Exception e1) {         
                log.error("对象转json出错。", e1);
            } 
        }
    }
    
    /**
     * 文件上传
     * <p>文件上传-文件信息存数据库
     * @param request
     * @param response
     * @throws Exception
     */
    public void uploadFileWithDB(HttpServletRequest request, HttpServletResponse response) throws Exception   {
    	    Map<String,Object> result = new HashMap<String,Object>();
        	// 获取表单域
            Map<String,Object> fieldMap = getFormField(request);
            
            FileItem fileItem = (FileItem) fieldMap.get("uploadFile"); //上传文件
            String mTName = (String) fieldMap.get("mTname"); //模块名称
            log.info("[FileManagerServlet | upload] 获取文件上传参数:" + fieldMap);
            // 保存文件
            String rootDir = getRootDir();// 文件根路径
            String sumDir =FileHelper.relativePath(fileItem.getName(),mTName, DBFLAG); // 子路径
            String savePath = rootDir + sumDir; // 全路径                       
            File file = new File(savePath);
            if (!file.getParentFile().exists()) {//创建文件的父文件夹
               file.getParentFile().mkdirs();
            }
            fileItem.write(file);
            Map<String,String> map = new HashMap<String,String>();
            map.put("fileName", fileItem.getName());//文件名称
            map.put(FILE_PATH, sumDir);//文件相对路径
            result.put(IticConst.DATA, map);
            result.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
            responseJson(response, result);       
    }
    
    /**
     * 删除文件
     * <p>根据文件路径删除对应文件
     * @param request
     * @param response
     * @throws IOException 
     */
    public void deleteFile(HttpServletRequest request, HttpServletResponse response) throws IOException{ 
        String filePath = request.getParameter(FILE_PATH);
        String result = "";
        if (StringHelper.isNotBlank(filePath)) {
        	String rootDir = getRootDir();
            File file = new File(rootDir + filePath);
            if (file.exists()) {//删除文件
                if(file.delete()){//删除成功
                    result = ResponseCode.SUCCESS.getCode();
                }else{
                    result = ResponseCode.SERVER_ERROR.getCode();
                }
            }else{
            	 result = ResponseCode.PARAM_INVALID.getCode();
            }
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }                    
        responseJson(response, result); 
    }

    /**
     * 文件下载
     * @param request
     * @param response
     * @throws IOException 
     */
	public void downLoadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String filePath = request.getParameter(FILE_PATH);
		if (StringHelper.isNotBlank(filePath)) {
			String path = getRootDir() + filePath;//获取下载文件的路径
			File file = new File(path);
			if(file.exists()){
			    downLoadFile(file, request, response);//下载文件
			}else{
			    responseText(response, ResponseCode.PARAM_INVALID.getCode());
			}
		}else{
            responseText(response, ResponseCode.PARAM_INVALID.getCode());
		}
	}
	/**
	 * 下载文件
	 * @param file 文件
	 * @param request 
	 * @param response
	 * @throws IOException 
	 */
	private void downLoadFile(File file,HttpServletRequest request, HttpServletResponse response) throws IOException{
	    InputStream inputStream = null;
	    OutputStream outputStream = null;
	    try {
            String filename = file.getName();//文件名
            inputStream = new BufferedInputStream(new FileInputStream(file));
            response.reset();// 清空response
            response.setContentType("application/octet-stream");//设置response的Header
            filename = toUtf8String(request, filename.replace(" ", ""));
            response.addHeader("Content-Disposition","attachment;filename="+ filename);
            response.addHeader("Content-Length", "" + file.length());
            outputStream = new BufferedOutputStream(response.getOutputStream());
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, length);
            }
        }catch (Exception e) {
            log.info("FileManagerServlet|downFile(文件下载)出现异常",e);
            throw new RuntimeException(ResponseCode.SERVER_ERROR.getCode(),e);
        }finally{//关闭流
            if(inputStream!=null){
                inputStream.close();
            }
            if(outputStream!=null){
                outputStream.flush();
                outputStream.close();
            }
        }
	}
	/**
	 * 将图片文件写入response中传递到前台
	 * @param filePath
	 * @return
	 * @throws IOException 
	 */
	public void showImagesFile(HttpServletRequest request,HttpServletResponse response) throws IOException  {
	    String filePath = request.getParameter(FILE_PATH);
		if(StringHelper.isNotBlank(filePath)) {
		    filePath = getRootDir() + filePath;
			FileInputStream fi = null;
			OutputStream out = null;
			try {
				File swfFile = new File(filePath);
				if(swfFile.exists()){
					log.info("文件已验证，存在。");
					fi = new FileInputStream(swfFile);
					// 设置响应头和保存文件名
					String suffix = filePath.substring(filePath
							.lastIndexOf(".") + 1);
					response.setContentType(getMime(suffix));
					response.setHeader("Pragma","No-cache");    
					response.setHeader(CACHE_CONTROL,IS_CACHE);    
					response.setDateHeader("Expires", -10);
					// 写出流信息
					int b = 0;
					out = response.getOutputStream();
					while ((b = fi.read()) != -1) {
						out.write(b);
					}
					log.info("文件流成功输出到前台。");
				}else{
		            log.info("FileManagerServlet|showImagesFile（获取图片)：路径("+filePath+")下的图片不存在");
				    responseText(response, ResponseCode.PARAM_INVALID.getCode());
				}
			} catch (Exception e) {
                log.error("FileManagerServlet|showImagesFile（获取图片)出现错误",e);
			} finally{
				if (fi != null){
					fi.close();
				}
				if(out!=null){
					out.flush();
					out.close();
				}
			}
		}else{
		   responseText(response, ResponseCode.PARAM_INVALID.getCode());
		}
	}
	
	/**
	 * 查询根目录下的所有文件
	 * @param request
	 * @param response
	 * @throws Exception
	 * @return void
	 * @throws IOException 
	 */
    public void listFile(HttpServletRequest request, HttpServletResponse response) throws IOException{ 
            Map<String, Object> dataMap = new HashMap<String, Object>();
            String result = "";
            String folderPath = request.getParameter(FILE_PATH);//获取源文件夹下的所有文件
            String zzjgdm = request.getParameter(ZZJGDM);//组织机构代码
            String rootDir = getRootDir();//文件夹根路径
            
            User user = (User) request.getSession(true).getAttribute(IticConst.PS_SESSION_USERINFO_KEY);
            // 权限校验
            if(null == user){
                result="no-admin";
            }else {
                List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
                String path = StringHelper.isNotBlank(folderPath)?(rootDir+folderPath):(rootDir+zzjgdm);//指定目录路径
                log.info("FileManagerServlet|listFile(获取文件)：指定目录为"+path);
                File dir = new File(path);//获取指定路径的文件夹
                if(dir.exists()){
                    File[] filelist = dir.listFiles();//获取该文件夹下面的所有文件
                    //文件夹里面的文件按时间排序
                    List<File> fileList = fileSort(filelist);
                    
                    for (int i = 0; i < filelist.length; i++) {
                        Map<String, Object> resultMap = new HashMap<String, Object>();
                        File childFile = fileList.get(i);
                        String fileName = childFile.getName() == null ? "": childFile.getName();// 文件名称
                        
                        long modifiedTime = childFile.lastModified();//获取文件的最后修改时间
                        Date lastUpdate=new Date(modifiedTime);
                        String filePath = childFile.getAbsolutePath(); // 全路径 
                        String fileType = "";//文件类型
                        String fileSize = "";//文件大小
                        String folderNotNull="yes";
                        if(childFile.isDirectory()){//该文件是文件夹
                            fileType = "folder";
                            fileSize =FileHelper.modifyByte(String.valueOf(FileUtils.sizeOfDirectory(childFile)));
                            //判断是否为空文件夹
                            if("0.0B".equals(fileSize)){
                            	folderNotNull="no";
                            }
                        }else{
                            int index = fileName.lastIndexOf(".");
                            fileType = getFileType(fileType, index, fileName);
                            if(index!=-1){//文件
                                fileType=fileName.substring(index+1); //文件类型
                            }
                            fileSize = FileHelper.getFileSize(filePath);//获取文件大小
                        }
                        
                        resultMap.put("name", fileName);// 文件名称
                        resultMap.put("date", DateHelper.formatDateTime(lastUpdate));// 修改时间
                        resultMap.put("size", fileSize);// 文件大小
                        resultMap.put("type", fileType);// 文件类型
                        resultMap.put("folderNotNull", folderNotNull);// 文件夹是否为空
                        resultMap.put(FILE_PATH,filePath.substring(rootDir.length()));// 文件路径
                        dataList.add(resultMap);
                    }
                    result = ResponseCode.SUCCESS.getCode();
                    dataMap.put(IticConst.DATA, dataList);
                }else{
                    log.info("[FileManagerServlet | listFile] : "+path+"下的文件不存在");
                    result = "not_exists";//文件不存在
                }
            }
            
            dataMap.put(IticConst.RESULT, result);
            responseJson(response, dataMap);
    }
    
    /**
     * 获得文件类型
     * @param fileType
     * @param index
     * @param fileName
     * @return
     */
    private String getFileType(String fileType, int index, String fileName){
        String newFileType = fileType;
        if (index != -1){//文件
            newFileType = fileName.substring(index+1); //文件类型
        }
        return newFileType;
    }
    
    /**
     * 新建文件夹
     * @param request
     * @param response
     * @throws IOException 
     */
    public void createFolder(HttpServletRequest request, HttpServletResponse response) throws IOException { 
        String folderPath = request.getParameter(FILE_PATH);//源文件夹路径
        String zzjgdm = request.getParameter(ZZJGDM);//组织机构代码
        String folderName = request.getParameter("fileName");//新建文件夹名称
        Map<String, Object> dataMap = new HashMap<String, Object>();
        String result = null;
        User user = (User) request.getSession(true).getAttribute(IticConst.PS_SESSION_USERINFO_KEY);
        // 权限校验
        result = checkAuthorty(user, zzjgdm);
        if(StringHelper.isBlank(result)){
            if (StringHelper.isNotBlank(folderName)&&StringHelper.isNotBlank(zzjgdm)) {
                String rootDir = getRootDir();//文件夹根路径
                
                String sumDir = null; //子路径
                if(StringHelper.isNotBlank(folderPath)){
                    sumDir = FileHelper.relativePath(folderName, folderPath, !DBFLAG);
                }else{
                    sumDir = FileHelper.relativePath(folderName, zzjgdm, !DBFLAG);
                }
                String savePath = rootDir + sumDir; // 全路径 
                File file = new File(savePath);
                //创建文件保存的根路径
                if (!file.getParentFile().exists()) {//创建文件的父文件夹
                    file.getParentFile().mkdirs();
                }
                
                if (!file.exists()) {//文件夹不存在
                    if(!file.mkdirs()){//文件夹创建失败
                        result = "create_failure";
                        log.info("[FileManagerServlet | createFolder] ："+savePath+"文件夹创建失败");
                    }else{
                        result = ResponseCode.SUCCESS.getCode();
                    }
                }else{//文件夹已存在
                    result = ResponseCode.EXIST.getCode();
                    log.info("[FileManagerServlet | createFolder] ：该路径("+savePath+")下的文件夹已存在");
                }
            }else {
                result = ResponseCode.PARAM_INVALID.getCode();
                log.info("[FileManagerServlet | createFolder] ：文件夹名称("+folderName+")不能为空");
            }  
        }
        dataMap.put(IticConst.RESULT, result);
        responseJson(response, dataMap);
    }
    /**
     * 文件重命名
     * @param request
     * @param response
     * @throws IOException 
     */
    public void reNameFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String filePath = request.getParameter(FILE_PATH);//老路径
        String newPath = request.getParameter("newPath");//新路径
        String zzjgdm =request.getParameter("zzjgdm");//组织机构代码
        Map<String,String> dataMap=new HashMap<String,String>();
        String result = null;
        User user = (User) request.getSession(true).getAttribute(IticConst.PS_SESSION_USERINFO_KEY);

        // 权限校验
        result = checkAuthorty(user, zzjgdm);
        if(StringHelper.isBlank(result)){
            if(StringHelper.isNotBlank(filePath)&&StringHelper.isNotBlank(newPath)){
                String dirPath = getRootDir()+zzjgdm;//根目录路径
                if(new File(dirPath+newPath).exists()){
                    log.info("[FileManagerServlet | reNameFile] ：该路径("+newPath+")下的文件已存在");
                    result = ResponseCode.EXIST.getCode();
                }else{
                    //重命名
                    boolean flag = FileHelper.renameFile(dirPath+filePath,dirPath+newPath);
                    if(flag){//成功
                        result = ResponseCode.SUCCESS.getCode();
                        log.info("文件重命名成功");
                    }else{//失败
                        result = "reName_failure";
                        log.info("文件重命名失败");
                    }
                }
            }else{
                result = ResponseCode.PARAM_INVALID.getCode();
                log.info("[FileManagerServlet | reNameFile] ：文件路径("+filePath+")"+"("+newPath+")不能为空");
            }
        }
        dataMap.put(IticConst.RESULT, result);
        responseJson(response, dataMap); 
    }
    /**
     * 删除文件夹
     * @param request
     * @param response
     * @return void
     * @throws IOException 
     */
    public void deleteFolder(HttpServletRequest request, HttpServletResponse response) throws IOException { 
        String result = null;
        String folderPath = request.getParameter(FILE_PATH);//源文件夹路径
        try {
            if(StringHelper.isNotBlank(folderPath)){
                String rootDir = getRootDir();//获取根路径
                File file = new File(rootDir+folderPath);
                if(file.exists()){//文件存在
                    FileUtils.deleteDirectory(file);//删除文件夹
                    result = ResponseCode.SUCCESS.getCode();
                }else{
                    result = ResponseCode.PARAM_INVALID.getCode();
                    log.info("[FileManagerServlet | deleteFolder] ：该路径("+folderPath+")下的文件不存在");
                }
            }else{
                result = ResponseCode.PARAM_INVALID.getCode();
                log.info("[FileManagerServlet | deleteFolder] ：文件路径("+folderPath+")不能为空");
            }
        } catch (Exception e) {
            result = ResponseCode.SERVER_ERROR.getCode();
            log.info("[FileManagerServlet | deleteFolder] 服务异常", e);
        }
        responseJson(response, result); 
    }
    
    /**
     * 文件夹下载
     * @param request
     * @param response
     * @throws IOException 
     */
    public void downFolder(HttpServletRequest request, HttpServletResponse response) throws IOException  {
        String filePath = request.getParameter(FILE_PATH);//获取文件下载路径
        if(StringHelper.isNotBlank(filePath)){
            String path = getRootDir() + filePath;
          //压缩文件到rootDir中的zip中
            //客户端下载
            File[] files=new File(path).listFiles();
            long i=files.length;
            if(i!=0) {
                ZipHelper.zip(path, path + ".zip");
                
                File file = new File(path + ".zip");//获取压缩的文件
                if(file.exists()){
                    downLoadFile(file, request, response);
                    //删除压缩的zip包
                    FileHelper.delFile(path + ".zip");
                }else{
                    log.info("[FileManagerServlet | downFolder] ：该路径("+filePath+")下的文件不存在");
                    responseText(response, ResponseCode.PARAM_INVALID.getCode());
                }
            }else{
                responseText(response, "文件夹不能为空");
            }
        }else{
            log.info("[FileManagerServlet | downFolder] ：文件路径("+filePath+")不能为空");
            responseText(response, ResponseCode.PARAM_INVALID.getCode());
        }
    }
   
    /**
     * 文件上传
     * <p>文件上传-文件信息不保存到数据库
     * @param request
     * @param response
     * @return void
     * @throws IOException 
     */
    public void uploadFileWithOutDB(HttpServletRequest request, HttpServletResponse response) throws IOException{
        String result = null;
        try {
                User user = (User) request.getSession(true).getAttribute(IticConst.PS_SESSION_USERINFO_KEY);
                // 获取表单域
                Map<String,Object> fieldMap = getFormField(request);
                String folderPath = (String) fieldMap.get(FILE_PATH); //源文件夹路径
                String zzjgdm = (String) fieldMap.get(ZZJGDM); //组织机构代码
                FileItem fileItem = (FileItem) fieldMap.get("uploadFile");  // 上传文件
                if(StringHelper.isNotBlank(zzjgdm)){
                    // 权限校验
                    result = checkAuthorty(user, zzjgdm);
                    if(StringHelper.isBlank(result)){
                        String sumDir = null; //子路径
                        if(StringHelper.isNotBlank(folderPath)){
                            sumDir = FileHelper.relativePath(fileItem.getName(), folderPath, !DBFLAG);
                        }else{
                            sumDir = FileHelper.relativePath(fileItem.getName(), zzjgdm, !DBFLAG);
                        }
                        File file = new File(getRootDir() + sumDir);
                        //创建文件保存的根路径
                        if (!file.getParentFile().exists()) {//创建文件的父文件夹
                            file.getParentFile().mkdirs();
                        }
                        fileItem.write(file);
                        // 保存文件
                        result = ResponseCode.SUCCESS.getCode();
                        log.info("[FileManagerServlet | uploadFileWithOutDB] 文件上传成功");
                    }
                }else{
                    result = ResponseCode.PARAM_INVALID.getCode();
                    log.info("[FileManagerServlet | uploadFileWithOutDB]组织机构代码不能为空");
                }
        } catch (Exception e) {
            result = ResponseCode.SERVER_ERROR.getCode();
            log.info("[FileManagerServlet | uploadFileWithOutDB]文件上传失败，服务异常",e);
       }
        responseText(response, result);       
    }
    
    /**
     * 下载文件
     * <p>根据文件类型（单个文件或者文件夹），调用不同的方法下载文件
     * @param request
     * @param response
     * @throws IOException 
     */
    public void downFolderOrFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String filePath = request.getParameter(FILE_PATH);//文件或者文件夹路径
        if(StringHelper.isNotBlank(filePath)){
            String path = getRootDir() + filePath;//全路径
            File file = new File(path);
            if(file.exists()){
                if(file.isDirectory()){//判断是否是文件夹
                    downFolder(request, response);
                }else{
                    downLoadFile(request, response);
                }
            }else{//文件不存在
                log.info("[FileManagerServlet | downFolderOrFile] ：路径("+filePath+")下的文件不存在");
                responseText(response, ResponseCode.PARAM_INVALID.getCode());   
            }
        }else{
            log.info("[FileManagerServlet | downFolderOrFile] ：文件路径("+filePath+")不能为空");
            responseText(response, ResponseCode.PARAM_INVALID.getCode());       
        }
    }
    /**
     * 删除文件
     * <p>根据文件类型（单个文件或者文件夹），调用不同的方法删除文件
     * @param request
     * @param response
     * @throws IOException 
     */
    public void delFolderOrFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String filePath = request.getParameter(FILE_PATH);//文件或者文件夹路径
        if(StringHelper.isNotBlank(filePath)){
            String path = getRootDir() + filePath;//全路径
            File file = new File(path);
            if(file.exists()){
                if(file.isDirectory()){//判断是否是文件夹
                    deleteFolder(request, response);//删除文件夹
                }else{
                    deleteFile(request, response);//删除文件
                }
            }else{//文件不存在
                log.info("[FileManagerServlet | delFolderOrFile] ：路径("+filePath+")下的文件不存在");
                responseJson(response, "no_exists");   
            }
        }else{
            log.info("[FileManagerServlet | delFolderOrFile] ：文件路径("+filePath+")不能为空");
            responseJson(response, ResponseCode.PARAM_INVALID.getCode());//参数不合法      
        }
    }
    
    /**
     * 集合按时间排序
     * <p>获取目录下所有文件(按修改时间倒叙排序)
     * @param filelist
     * @return
     */
    private static List<File> fileSort(File[] filelist) {
        List<File> list = new ArrayList<File>(Arrays.asList(filelist));
        if (list != null && !list.isEmpty()) {
            Collections.sort(list, new Comparator<File>() {
                @Override
                public int compare(File file, File newFile) {
                    if (file.lastModified() < newFile.lastModified()) {
                        return 1;
                    } else if (file.lastModified() == newFile.lastModified()) {
                        return 0;
                    } else {
                        return -1;
                    }
 
                }
            });
        }
        return list;
    }
    /**
     * 获得SWF文件对应的Mime类型
     * @param suffix
     * @return
     */
    private String getMime(String suffix) {
        Map<String, String> mimeMap = new HashMap<String, String>();
        mimeMap.put("swf", "application/x-shockwave-flash");
        mimeMap.put("jpg", "image/jpeg");
        mimeMap.put("jpeg", "image/jpeg");
        mimeMap.put("png", "image/jpeg");
        mimeMap.put("bmp", "image/jpeg");
        mimeMap.put("flv", "flv-application/octet-stream");
        mimeMap.put("avi", "video/avi");
        mimeMap.put("rmvb", "application/vnd.rn-realmedia-vbr");
        if (!StringHelper.isBlank(suffix)) {
            if (mimeMap.containsKey(suffix)) {
                return mimeMap.get(suffix);
            } else {
                return "";
            }
        } else {
            return "";
        }
    }
    /**
     * 获取上传文件根目录
     * </br>格式:
     * </br>     用户主目录/项目编号_fileupload(若未配置项目编号则为fileupload)
     * @return 文件上传根目录
     */
    private static String getRootDir() {
        return FileHelper.getRootDir();
    }
    /**
     * 文件名编码转换
     * </br>IE的话，通过URLEncoder对filename进行UTF8编码。
     * </br>而其他的浏览器（firefox、chrome、safari、opera），则通过字节转换成ISO8859-1
     * @param request
     * @param filename 文件名
     * @return String
     */
    private static String toUtf8String (HttpServletRequest request,String filename){
        String agent = request.getHeader("User-Agent"); //获取浏览器类型
        String newFileName = "";
        try {
            if ((agent != null && agent.indexOf("MSIE") != -1)) {
                newFileName = URLEncoder.encode(filename, CHARACTER_ENCODING);
            } else {
                newFileName = new String(filename.getBytes(CHARACTER_ENCODING), "ISO8859-1");
            }
        } catch (UnsupportedEncodingException e) {
            log.info("FileManagerServlet|toUtf8String：转换异常", e);
        }
        return newFileName;
    }
    
    /**
     * 获取文件上传请求的表单字段
     * @param request
     * @return
     * @throws FileUploadException 
     * @throws UnsupportedEncodingException 
     */
    private Map<String, Object> getFormField(HttpServletRequest request) throws FileUploadException, UnsupportedEncodingException  {
        // 判断是否为文件上传请求
        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new RuntimeException("Not an Multipart request!");               
        }        
        log.info("[FileManagerServlet | getFormField] try to parse multipart request.");
        // 设置临时文件缓冲区
        String path = this.getServletContext().getRealPath("/");             
        DiskFileItemFactory diskFactory = new DiskFileItemFactory();
        diskFactory.setSizeThreshold(10 * 1024 * 1024);
        diskFactory.setRepository(new File(path + "/temp"));
        
        // 解析request
        ServletFileUpload upload = new ServletFileUpload(diskFactory);                
        List<FileItem> list = upload.parseRequest(request);
        Map<String, Object> fieldMap = new HashMap<String, Object>();
        for (FileItem item : list) {
            if (item.isFormField()) {
                fieldMap.put(item.getFieldName(), item.getString(CHARACTER_ENCODING));
            } else {
                fieldMap.put(item.getFieldName(), item);
            }
        } 
        log.info("[FileManagerServlet | getFormField] parse multipart request complete, form field:" + fieldMap);
        return fieldMap;
    }
    
    /**
     * object转为json串
     * @param response
     * @param jsonObject 需要转json的object对象
     * @throws IOException 
     */
    private static void responseJson(HttpServletResponse response, Object jsonObject) throws IOException {
        response.setContentType("application/json; charset=UTF-8");
        response.setHeader(CACHE_CONTROL, IS_CACHE);
        response.setCharacterEncoding(CHARACTER_ENCODING);
        String jsonStr = "";
        ObjectMapper mapper = new ObjectMapper();
        if (jsonObject instanceof String) {
           Map<String, Object> resultMap = new HashMap<String, Object>();
           resultMap.put(IticConst.RESULT, jsonObject);
           jsonStr = mapper.writeValueAsString(resultMap);
        } else {
           jsonStr = mapper.writeValueAsString(jsonObject);
        }
        response.getWriter().write(jsonStr);
        response.getWriter().flush();
    }
    /**
     * string转json
     * @param response
     * @param text 需要转json的字符串
     * @throws IOException
     */
    private static void responseText(HttpServletResponse response, String text) throws IOException {
        response.setContentType("text/plain; charset=UTF-8");
        response.setHeader(CACHE_CONTROL, IS_CACHE);
        response.setCharacterEncoding(CHARACTER_ENCODING);
        response.getWriter().write(text);
    }
    /**
     * 获取session中用户信息
     * @param request
     * @return
     */
    private User findUserSession(HttpServletRequest request) {
        Object obj = request.getSession().getAttribute(
                IticConst.PS_SESSION_USERINFO_KEY);
        if (obj instanceof User) {
            return (User) obj;
        }
        return null;
    }
    
    /**
     * 校验权限
     * 
     * @param user
     * @param zzjgdm
     * @return String
     */
    private String checkAuthorty(User user, String zzjgdm) {
        String result = "";
        if (user == null) {
            result = ResponseCode.NOT_LOGIN.getCode(); 
            log.info("[UploadFileServlet | checkAuthorty] ：该用户未登陆");
        } else {
            if (StringUtils.isNotBlank(zzjgdm)) {
                if (!user.getOrganizationCode().equals(zzjgdm)) {
                    result = "no_authorty";// 没有权限
                    log.info("[UploadFileServlet | checkAuthorty] ：该用户(" + user.getRealname() + ")没有操作权限");
                }
            } else {
                result = ResponseCode.PARAM_INVALID.getCode();// 参数不合法
                log.info("[UploadFileServlet | checkAuthorty] ：组织机构码(" + zzjgdm + ")不能为空");
            }
        }
        return result;
    }
}
